<template>
  <BasicDrawer
    v-bind="$attrs"
    @register="registerDrawer"
    showFooter
    destroyOnClose
    :title="getTitle"
    width="70%"
    @ok="handleSubmit"
  >
    <Spin :spinning="loading">
      <BasicForm @register="registerForm" @field-value-change="handleChangeFeild">
        <template #modType="{ model, field }">
          <RadioButtonGroup
            v-model:value="model[field]"
            @change="changeModtype"
            :options="[
              {
                label: '目录菜单',
                value: 0,
              },
              { label: '功能菜单', value: 1 },
            ]"
          />
        </template>
      </BasicForm>
      <div class="mt-2 p-4">
        <!-- <ActionAuth :moduleId="moduleId" v-model:data="actionAuths" @success="handleSuccess" /> -->
        <MTable
          :columns="columnData"
          v-model:data="actionAuths"
          @add="handleAdd"
          @edit="handleEdit"
        />
      </div>
      <ActionAuthModal @register="registerModal" @success="handleSuccess" />
      <!-- <AddAuthModal @register="registerModal" @success="handleSuccess" /> -->
    </Spin>
  </BasicDrawer>
</template>
<script lang="ts">
  import ActionAuthModal from './ActionAuthModal.vue';
  import MTable from './MTable.vue';
  import { defineComponent, ref, computed, unref } from 'vue';
  import { BasicForm, useForm, RadioButtonGroup } from '/@/components/Form/index';
  import { Spin } from 'ant-design-vue';
  import { BasicDrawer, useDrawerInner } from '/@/components/Drawer';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { useModal } from '/@/components/Modal';
  import {
    useTable,
    // TableAction,BasicTable,
  } from '/@/components/Table';
  // import AddAuthModal from './AddAuthModal.vue';
  // import ActionAuth from './ActionAuth.vue';

  import { formSchema, columnsAuth } from './menu.data';
  import { getMenuTree } from '/@/api/admin/menu';
  // import { getMenuTree, addMenuApi, updateMenuApi, getMenuItemApi } from '/@/api/admin/menu';
  import { getMetaMenuItemApi, updateMetaMenuApi, addMetaMenuApi } from '/@/api/database/metadata';
  import { deleteModuleAuthApi } from '/@/api/admin/auth';
  import { actionAuths2 as columns } from './menu.data';
  export default defineComponent({
    name: 'MenuDrawer',
    components: {
      ActionAuthModal,
      MTable,
      Spin,
      BasicDrawer,
      BasicForm,
      // BasicTable,
      // TableAction,
      // ActionAuth,
      RadioButtonGroup,
    },
    emits: ['success', 'register'],
    setup(_, { emit }) {
      const loading = ref(false);
      const isUpdate = ref(false);
      const isModelAuth = ref(false);
      const isModelBind = ref(false);
      const moduleId = ref();
      const columnData = ref(columns);
      let temp;
      const actionAuths = ref<any>([]);
      const { createMessage } = useMessage();
      const [registerForm, { resetFields, setFieldsValue, updateSchema, validate }] = useForm({
        labelWidth: 160,
        schemas: formSchema((v) => {
          if (!isUpdate.value) {
            setFieldsValue({
              orignName: v,
            });
          }
        }),
        showActionButtonGroup: false,
        baseColProps: { lg: 11, md: 23 },
      });

      async function getMenuItem(moduleId) {
        const res = await getMetaMenuItemApi(moduleId);
        const { module, moduleUserTypes, usingHandles, fields } = res;
        fields?.forEach((e) => {
          if (e.isUnique == 'false' || e.isUnique == '0') {
            e.isUnique = false;
          }
          if (e.isnullable == 'false' || e.isnullable == '0') {
            e.isnullable = false;
          }
          if (e.pkey == 'false' || e.pkey == '0') {
            e.pkey = false;
          }
          if (e.isUnique == 'true' || e.isUnique == '1') {
            e.isUnique = true;
          }
          if (e.isnullable == 'true' || e.isnullable == '1') {
            e.isnullable = true;
          }
          if (e.pkey == 'true' || e.pkey == '1') {
            e.pkey = true;
          }
        });
        actionAuths.value = fields || [];
        return { res, module, moduleUserTypes, usingHandles, fields };
      }

      const [registerDrawer, { setDrawerProps, closeDrawer }] = useDrawerInner(async (data) => {
        resetFields();
        loading.value = false;
        setDrawerProps({ confirmLoading: false });
        isUpdate.value = !!data?.isUpdate;

        if (unref(isUpdate)) {
          moduleId.value = data.record.tableId;
          // return;
          const { res, module } = await getMenuItem(moduleId.value);
          temp = res;
          console.log(
            '%cmodule===>141： ',
            'background: rgb(23, 197, 237,.6); color: #ff5023; font-size:18px;font-weight:700',
            module,
          );

          setFieldsValue(res);
          if (module?.modelClassify) {
            //  需要初始化重置
            setFieldsValue({ listModelId: module.listModelId });
          }
        } else {
          resetFields();
          actionAuths.value = [];
          temp = {};
        }
        const children = await getMenuTree();
        updateSchema([
          {
            field: 'moduleId',
            ifShow: unref(isUpdate),
          },
          {
            field: 'parentId',
            componentProps: { treeData: [{ name: '根菜单', children, id: '-1' }] },
          },
        ]);
        loading.value = false;
        setDrawerProps({ confirmLoading: false });
      });
      // , { setTableData }
      const [registerTable] = useTable({
        columns: columnsAuth,
        pagination: false,
        striped: false,
        bordered: true,
        showIndexColumn: false,
        canResize: false,
        actionColumn: {
          width: 200,
          title: '操作',
          dataIndex: 'action',
          fixed: undefined,
        },
      });

      const [registerModal, { openModal }] = useModal();

      const getTitle = computed(() => (!unref(isUpdate) ? '新增' : '编辑'));
      // function toJson(str) {
      //   try {
      //     return JSON.parse(str || '{}');
      //   } catch (e) {
      //     return {};
      //   }
      // }
      async function handleSubmit() {
        // return;
        // alert('点击提交');
        // return;
        try {
          loading.value = false;
          // loading.value = true;
          const values = await validate();
          setDrawerProps({ confirmLoading: true });

          const apiFn = unref(isUpdate) ? updateMetaMenuApi : addMetaMenuApi;
          // values.typeFlag = 1;
          if (!unref(isUpdate)) {
            // values.typeRight = 1;
            // values.modRight = 1;
          }

          // const extMeta = toJson(values.extMeta);
          // values.tableType = 1;
          const params = Object.assign(temp || {}, values);
          params.fields = actionAuths.value;
          // 参数处理
          params?.fields?.forEach((e, ind) => {
            e.id = 1 + ind;
          });
          console.log('参数处理最新：', params);
          // return;
          await apiFn(params);
          createMessage.success('操作成功');
          closeDrawer();
          emit('success');
        } finally {
          loading.value = false;
          setDrawerProps({ confirmLoading: false });
        }
      }

      function handleAdd(record: Recordable) {
        openModal(true, {
          record,
          isUpdate: false,
        });
      }
      function handleEdit(record: Recordable) {
        openModal(true, {
          record,
          isUpdate: true,
        });
      }

      async function handleDelete(record: Recordable) {
        const { moduleId, userFlag } = record;
        await deleteModuleAuthApi(moduleId, userFlag);
        createMessage.success('操作成功');
        getMenuItem(moduleId);
      }

      function addAuthHandle() {
        openModal(true, {
          record: { moduleId: moduleId.value },
          idupdate: false,
        });
      }

      // function handleSuccess(param, isUpdate) {
      //   console.log('修改数据param:', param);
      //   console.log('修改数据isUpdate:', isUpdate);
      //   return;
      //   // getMenuItem(moduleId.value);
      // }
      function handleSuccess(param, isUpdate) {
        let newData = JSON.parse(JSON.stringify(actionAuths.value || []));
        if (isUpdate.value) {
          let ind = actionAuths.value.findIndex((e) => e.id === param.id);
          newData[ind] = param;
        } else {
          param.id = `${newData.length + 1}`;
          newData.push(param);
        }
        actionAuths.value = [...newData];
        emit('success', param, isUpdate);
      }
      function changeModtype(v) {
        isModelAuth.value = v === 1;
      }
      function handleChangeFeild(key, value) {
        if (key === 'modelClassify') {
          isModelBind.value = !!value;
        }
      }

      return {
        columnData,
        loading,
        isUpdate,
        getTitle,
        actionAuths,
        moduleId,
        isModelAuth,
        isModelBind,
        registerDrawer,
        registerForm,
        registerTable,
        registerModal,
        handleEdit,
        handleAdd,
        handleSubmit,
        handleDelete,
        addAuthHandle,
        handleSuccess,
        changeModtype,
        handleChangeFeild,
      };
    },
  });
</script>
